var express = require('express');
var router = express.Router();
let { messagemodel, loginMdel, friendmodel } = require('../model/cwp')
var multiparty = require('multiparty');

/* GET home page. */
router.get('/', function (req, res, next) {
	res.render('index', { title: 'Express' });
});
router.post("/register", async (req, res) => {
	const { user, password, role } = req.body;

	// 验证用户名是否已存在
	const existingUser = await loginMdel.findOne({ user });
	if (existingUser) {
		return res.send({
			code: 409,
			message: "用户名已存在"
		});
	}

	// 创建新用户
	const newUser = new loginMdel({ user, password, role });
	await newUser.save();

	res.send({
		code: 200,
		message: "注册成功"
	})
});

router.post("/login", async (req, res) => {
	let { user, password } = req.body;
	let note = await loginMdel.findOne({ user }).select("+password");
	if (!note) return res.send({ code: 500, message: "用户名不存在" });
	let isVaild = password === note.password;
	if (!isVaild) return res.send({ code: 501, message: "密码错误" });
	res.send({
		code: 200,
		message: "登录成功",
		note
	});
});

// 判断传入的用户是否存在
router.post('/isuser', async (req, res) => {
	let { user } = req.body
	if (await loginMdel.findOne({ user })) {
		res.send({
			code: 200
		})
	} else {
		res.send({
			code: 201,
			message: "用户名不存在,请先注册"
		})
	}
})

// 验证码
router.post('/getcode', async function (req, res, next) {
	let min = 100000 //最小值
	let max = 999999 //最大值
	let temp = Math.floor(Math.random() * (max - min + 1)) + min //生成100000-999999随机数
	let phone = req.body.phone
	console.log(phone, temp);

	// Depends on tencentcloud-sdk-nodejs version 4.0.3 or higher
	const tencentcloud = require("tencentcloud-sdk-nodejs-sms");

	const SmsClient = tencentcloud.sms.v20210111.Client;

	// 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
	// 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
	// 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
	const clientConfig = {
		credential: {
			// 密钥id
			secretId: "AKIDdCakklpofOuRyLWXRKSVRBgx00ax9D7o",
			// 密钥密码
			secretKey: "aw64qMekdHkqjOo10oPsCLGyUp02sVvA",
		},
		region: "ap-beijing",
		profile: {
			httpProfile: {
				endpoint: "sms.tencentcloudapi.com",
			},
		},
	};

	// 实例化要请求产品的client对象,clientProfile是可选的
	const client = new SmsClient(clientConfig);
	const params = {
		"PhoneNumberSet": ["+86" + phone],
		"SmsSdkAppId": "1400845806", //应用id
		"SignName": "空间不吃饭公众号", //公众号
		"TemplateId": "1890119", //正文模板id
		"TemplateParamSet": [temp.toString()]
	};

	client.SendSms(params).then(
		(data) => {
			// if (data.Code == 'Ok') {
			res.send({ code: 200, msg: "验证码发送成功", yanZhengMa: temp.toString() })
			// }
			// res.send({ code: 200, msg: "验证码发送成功", yanZhengMa: temp.toString(), Data })
		},
		(err) => {
			console.error("error", err);
		}
	);
})

// 修改密码
// 判断接收到的密码和原来的密码是否一致
router.post('/changepassword', async function (req, res, next) {
	let { phone, password } = req.body
	if (await loginMdel.findOne({ user: phone })) {
		let note = await loginMdel.findOne({ user: phone }).select("+password");
		let isVaild = password === note.password;
		if (isVaild) {
			res.send({ code: 201, msg: "密码和原密码一样，禁止修改" })
		} else {
			// await loginMdel.updateOne({ user: phone }, { password })
			res.send({ code: 200, msg: "密码修改成功" })
		}
	}
})

//获取消息
router.get('/getmessage', async function (req, res, next) {
	// let toid = req.query.toid
	// let myid = req.query.myid
	// let mydata = await messagemodel.find({ myid: { $in: [myid, toid] } })
	// let myyou = mydata.filter((item, index) => {
	//   return (item.myid == myid || item.myid == toid) && (item.toid == myid || item.toid == toid)
	// })
	let myyou = await messagemodel.find()
	res.send(myyou)
})

// 根据登录的用户查找好友
router.post('/getfriend', async function (req, res, next) {
	let myid = req.body.myid
	let mydata = await friendmodel.find({ myid })
	let myyou = mydata.filter((item, index) => {
		return item.myid == myid
	})
	res.send(myyou)
})

const fs = require('fs');

router.post('/getImg', async (req, res, next) => {
	let form = new multiparty.Form();
	form.uploadDir = "upload";

	form.parse(req, async (err, fields, files) => {
		if (files && files.file) {
			const file = files.file[0];
			const oldPath = file.path;
			const customFileName = files.file[0].originalFilename; // 设置自定义的文件名
			const newPath = `${form.uploadDir}/${customFileName}`;

			fs.rename(oldPath, newPath, (err) => {
				if (err) {
					console.log(err);
					// 处理重命名失败的情况
				} else {
					// 重命名成功
					console.log(`File saved as ${customFileName}`);
					// 其他处理逻辑
				}
			});
		}
	});
});


router.post('/voice', (req, res) => {
	console.log(Buffer.from(req.body));
	// const audioData = req.body;

	// // 将Base64字符串转换为Buffer对象
	// const buffer = Buffer.from(audioData, 'base64');

	// // 将Buffer对象写入文件
	// const fileName = `audio-${new Date().getTime()}.wav`;
	// const filePath = `audio/${fileName}`;

	// fs.writeFile(filePath, buffer, (err) => {
	// 	if (err) {
	// 		console.error(err);
	// 		res.status(500).send('Failed to save audio file');
	// 	} else {
	// 		console.log(`Audio file saved as ${fileName}`);
	// 		res.send('Received and saved audio data');
	// 	}
	// });
});

// 引入multer
const multer = require('multer');
const upload = multer({ dest: './upload/audio' });
router.post('/upload', upload.single('audio'), (req, res) => {
	const { path } = req.file
	res.send({
		code: 200,
		msg: '上传成功',
		data: 'http://localhost:3000/upload/audio' + path
	})
});
module.exports = router;

// const { path } = req.file
// res.send({
// 	code: 200,
// 	msg: '上传成功',
// 	data: 'http://localhost:3000/' + path
// })